<template>
  <!--物资市场价 -->
  <div class="e-form">
    <div class="tabs" v-if="Object.keys(basicFormData).length != 0">
      <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
        <!-- 基本信息 -->
        <el-tab-pane
          label="基本信息"
          name="baseInfo"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="市场价记录"
          name="receivingMaterials"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <div>
          <!-- 基本信息 -->
          <div id="baseInfoCon" class="con">
            <div class="e-form">
                <BillTop title="物资市场价" @cancel="cancel"></BillTop>
              <div class="tabs">
                <div class="tabs-title" id="baseInfo">基本信息</div>
                <div style="width: 100%" class="form">
                  <el-form
                    :model="basicFormData"
                    label-width="150px"
                     ref="ruleForm"
                    :rules="rules"
                    class="demo-ruleForm"
                  >
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="物资编号：">
                          {{ basicFormData.materialNumber }}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="机构：">
                          {{ basicFormData.orgName }}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="物资类别：">
                          {{ basicFormData.materialClassName }}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="物资名称：" prop="materialName">
                          <el-input
                          v-model="basicFormData.materialName"
                        >
                        </el-input>
                         <el-button
                                type="primary"
                                style="background: #2e61d7;margin-left:5px;"
                                @click="Select()"
                                >选择</el-button
                            >
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="规格：">
                          {{ basicFormData.spec }}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="材质：">
                          <el-input v-model="basicFormData.texture"></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="市场参考价：">
                          {{ basicFormData.marketPrice }}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="网上价格：">
                          {{ basicFormData.onlinePrice }}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                           <el-form-item label="录入人：">
                          {{ basicFormData.founderName }}
                        </el-form-item>

                      </el-col>
                      <el-col :span="12">
                          <el-form-item label="启用：">
                          <el-switch
                            v-model="basicFormData.isEnable"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                          >
                          </el-switch>
                        </el-form-item>
                      </el-col>
                    </el-row>
                     <el-row>
                        <el-form-item label="单位：">
                          {{basicFormData.unit}}
                          </el-form-item>
                        </el-row>
                    <el-row>
                      <el-form-item label="备注：">
                        <el-input
                          type="textarea"
                          :rows="2"
                          placeholder="请输入内容"
                          v-model="basicFormData.remarks"
                        >
                        </el-input>
                      </el-form-item>
                    </el-row>
                  </el-form>
                </div>
              </div>
            </div>

            <!-- ------------------------------------------------------------------------------------- -->
          </div>

          <!-- 市场价记录 -->
          <div id="receivingMaterialsCon" class="con">
            <div class="tabs-title" id="receivingMaterials">市场价记录</div>
            <div class="e-table">
              <div class="top">
                <div class="left">
                  <div>
                    <el-button
                      size="small"
                      style="background: rgb(75, 178, 255); color: #fff"
                      @click="Add"
                      >新增</el-button
                    >
                  </div>
                </div>
              </div>
               <div class="errorMsg" v-if="errorMsg.length > 0">
                  <span v-for="(item, index) in errorMsg" :key="index">
                  {{ item }}
                  </span>
              </div>
              <el-table
                :data="marketPriceList"
                border
                style="width: 100%"
                :row-class-name="tableRowClassName"
                @cell-mouse-enter="cellMouseEnter"
                @cell-mouse-leave="cellMouseLeave"
                :cell-class-name="cellClsNm"
                :header-cell-style="{ textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }"
                :tree-props="{
                  children: 'children',
                  hasChildren: 'hasChildren',
                }"
                row-key="uuid"
                 ref="table"
                v-sortTable="{ 'tableData': marketPriceList, '_this': this, 'ref': 'table' }"
              >
                <el-table-column
                  fixed
                  type="index"
                  label="序号"
                  width="80"
                  align="center"
                >
                </el-table-column>
                 <el-table-column
                  label="操作"
                  fixed
                  width="100px"
                  align="left"
                >
                <template slot-scope="{ row }">
                    <div class="handle">
                        <div style=" cursor: pointer;">
                            <img src="@/assets/btn/delete.png"  @click="deleteEle(row)">
                        </div>
                    </div>
                </template>
                </el-table-column>
                <el-table-column
                  prop="addDate"
                  label="日期"
                  min-width="100"
                >
                    <template slot-scope="{ row  }">
                         <el-date-picker
                           @change="input(row)"
                            v-model="row.addDate"
                            type="date"
                            :placeholder= geyDate()
                            value-format="yyyy-MM-dd"
                            >
                            </el-date-picker>
                    </template>

                </el-table-column>
                <el-table-column
                  prop="marketPrice"
                  label="市场单价"
                  min-width="100"
                >
                 <template slot-scope="{ row  }">
                    <el-input
                     v-enter-float="{
                                set: row,
                                key: 'marketPrice'
                            }"
                     @input="input(row)"
                        v-model="row.marketPrice"
                    >
                    </el-input>
                </template>
                </el-table-column>
                <el-table-column prop="onlinePrice" label="网上价格" min-width="100">
                     <template slot-scope="{ row  }">
                        <el-input
                        @input="input(row)"
                            v-model="row.onlinePrice"
                        >
                        </el-input>
                </template>
                </el-table-column>
                <el-table-column prop="state" label="使用状态" width="100">
                  <template slot-scope="{ row  }">
                        {{['未使用','已使用'][row.state]}}
                </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </el-tabs>
    </div>
    <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    <div class="buttons">
      <el-button
        type="primary"
        style="background: #2e61d7"
        @click="save()"
        >保存</el-button
      >
      <el-button type="danger" size="small" @click="ctDelete" v-debounce v-if="!isAdd || !basicFormData.isEnable "
            >删除</el-button
        >
      <el-button @click="cancel()">关闭</el-button>
    </div>
  </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations } from 'vuex'
import {  selectDataClient  } from '@/utils/common'
import { AddMaterialsMarketPrice, EditMaterialsMarketPriceList, EditMaterialsMarketPrice } from '@/api/materials/materialsMarketPrice'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            userName: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: '',
            },
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
            marketPriceList: [], //市场价记录
            value: '',
            textarea: '',
            formData: {},
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            basicFormData: {
                'billId': '',
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'isEnable': true,
                'marketPrice': 0,
                'materialClassId': '',
                'materialClassName': '',
                'materialId': '',
                'materialName': '',
                'materialNumber': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'onlinePrice': 0,
                'orgId': '',
                'orgName': '',
                'spec': '',
                'texture': '',
                'unit': 'T'
            },
            objFlag: {
                flag5: false,
            },

            billid: '',
            orgId: '', //机构id
            orgName: '', //机构名称
            isSkip: false, //是否跳转
            orgIds: '',
            isAdd: false,
            id: '',
            UidArr: [],
            //验证
            rules: {
                materialName: [
                    { required: true, message: '请选择物资', trigger: 'change' },
                ],

            },

        }
    },
    computed: {
        judgeRoute () {
            if (this.$route.path.includes('Add')) {
                return false
            }
            return true
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },

    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    created () {
        this.basicFormData.orgId = this.$route.query.orgId
        this.basicFormData.orgName = this.$route.query.orgName
        this.billid = this.$route.query.billid
        this.basicFormData.founderId = localStorage.getItem('userId')
        this.basicFormData.founderName = localStorage.getItem('userName')
        this.isAdd = this.$route.query.isAdd

        if(!this.isAdd) {
            this.getBasicData() //基本信息
            this.getBasicDataList() //物资市场价记录
        }
    },
    mounted () {
    // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'receivingMaterials', 'accessory']
        this.tabArr = arr //标星星
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        //选择基础库
        Select () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/material/categoryLibrary/queryListByParentClassId2',
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                InitParamsStr: JSON.stringify(
                    {
                        'parentiId': 0,
                        'topClassNameNeed': ['主要材料'],
                    }
                ),
                Title: '物料选择'
            }).then(val=>{
                this.setSelectedInfo(val)
                val.forEach(item=>{
                    this.getId()
                    this.basicFormData.billId = this.UidArr[0]
                    this.basicFormData.materialNumber = item.billNo
                    this.basicFormData.materialClassId = item.classIdPath
                    this.basicFormData.materialClassName = item.classNamePath
                    this.basicFormData.materialId = item.billId
                    this.basicFormData.materialName = item.materialName
                    this.basicFormData.spec = item.spec
                    this.basicFormData.texture = item.texture
                    this.basicFormData.unit = item.unit
                })
            })
            // this.getId()
            // // this.basicFormData.billId = this.UidArr[0]
            // this.basicFormData.materialNumber = 'L.01.11.043'
            // this.basicFormData.materialClassId = 'a927247cb7b1-980c-724d-300a-7fdc7a5b/94c8544b-d743-4088-a65c-56eee970abec/a93c240b1cb0-a00f-2340-9e3a-aadbce7b'
            // this.basicFormData.materialClassName = '主要材料/桥梁专用材料/桥梁伸缩缝'
            // this.basicFormData.materialId = '000f1d4a-19ea-400a-b107-cd66aeeae2b2'
            // this.basicFormData.materialName = '桥梁伸缩缝'
            // this.basicFormData.spec = 'gqf-720'
            // this.basicFormData.texture = '哈哈哈'
            // this.basicFormData.unit = 'm'
        },
        //新增
        Add () {
            this.marketPriceList.unshift({
                'addDate': this.geyDate(),
                'billId': this.basicFormData.billId,
                'changeType': 1,
                'dtlId': '',
                'marketPrice': 0,
                'onlinePrice': 0,
                'state': 0
            })
        },
        // //保存
        // save () {
        //     if(this.isAdd === true) {   //新增
        //         const p1 = AddMaterialsMarketPrice(this.basicFormData)
        //         const p2 = EditMaterialsMarketPriceList(this.marketPriceList)
        //         Promise.all([p1, p2])
        //             .then(()=> {
        //                 this.clientPop('suc', '保存成功', this.cancel(), null, this.cancel() )
        //             })
        //     }else {  //编辑
        //         this.getPrice()
        //         const p1 = EditMaterialsMarketPrice(this.basicFormData)
        //         const p2 = EditMaterialsMarketPriceList(this.marketPriceList)
        //         Promise.all([p1, p2])
        //             .then(() => {
        //                 this.clientPop('suc', '保存成功', this.cancel(), null, this.cancel())
        //             })
        //     }
        // },
        //保存
        save () {
            this.errorList = []
            Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                .then(() => {
                    this.clientPop('suc', '保存成功', this.cancel(), null, this.cancel())
                })
                .catch(() => {
                    this.scorllError()
                })
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject) => {
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        if(this.isAdd === true) {   //新增
                            AddMaterialsMarketPrice(this.basicFormData)
                                .then(()=> {
                                    //  this.getBasicData() //更新基本信息
                                    resolve()
                                })
                                .catch(err => {
                                    this.setError('baseInfo')
                                    reject(err)
                                })
                        }else {  //编辑
                            this.getPrice()
                            EditMaterialsMarketPrice(this.basicFormData)
                                .then(() => {
                                    // this.getBasicData() //更新基本信息
                                    resolve()
                                })
                                .catch(err => {
                                    this.setError('baseInfo')
                                    reject(err)
                                })
                        }

                    } else {
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //更新明细
        updateBudgetDtl () {
            return new Promise((resolve, reject) => {
                this.verifyTable()
                    .then(() => {
                        if(this.isAdd === true) {   //新增
                            EditMaterialsMarketPriceList(this.marketPriceList)
                                .then(() => {
                                    resolve()
                                })
                                .catch(err => {
                                    this.setError('receivingMaterials')
                                    reject(err)
                                })
                        }else {  //编辑
                            this.getPrice()
                            EditMaterialsMarketPriceList(this.marketPriceList)
                                .then(() => {
                                    resolve()
                                })
                                .catch(err => {
                                    this.setError('receivingMaterials')
                                    reject(err)
                                })
                        }

                    })
                    .catch(err => {
                        this.setError('receivingMaterials')
                        reject(err)
                    })
            })
        },
        //明细非空验证
        verifyTable () {
            return new Promise((resolve, reject) => {
                this.errorMsg = []
                if(this.marketPriceList.length === 0) {
                    let str = '市场价记录不能为空！'
                    this.errorMsg.push(str)
                }
                else if (this.marketPriceList.length > 0) {
                    this.marketPriceList.forEach((item, index) => {
                        if (item.changeType !== -1) {
                            if (item.marketPrice === '' || item.marketPrice === null) {
                                let str = `请填写第 ${index + 1} 行的市场单价`
                                this.errorMsg.push(str)
                            }
                            if (item.onlinePrice === '' || item.onlinePrice === null) {
                                let str = `请填写第 ${index + 1} 行的网上价格`
                                this.errorMsg.push(str)
                            }

                        }

                    })
                }

                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                } else {
                    this.isErrorMsg = false
                    resolve()
                }
            })
        },
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        //更新价格
        getPrice () {
            this.marketPriceList.forEach(item=>{
                this.$set(this.basicFormData, 'marketPrice', item.marketPrice)
                this.$set(this.basicFormData, 'onlinePrice', item.onlinePrice)
            })
        },
        //
        input (row) {
            if(row.changeType === 1) {
                row.changeType = 1
            }else {
                this.$set(row, 'changeType', 2)
            }
            this.basicFormData.marketPrice = row.marketPrice
            this.basicFormData.onlinePrice = row.onlinePrice

        },

        //删除物资明细
        deleteEle (row) {
            if(row.state === 1) {
                this.clientPop('err', '该市场价数据已被使用，不允许删除!')
            }else{
                row.changeType = -1
            }
        },
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },

        //根据物资市场价id查询查询物资市场价基本信息
        getBasicData () {
            this.$Ajax
                .httpGet({
                    url: '/material/marketPrice/findById',
                    params: {
                        id: this.basicFormData.billId || this.billid,
                    },
                })
                .then(res => {
                    this.basicFormData = res
                })
        },
        //根据物资市场价id查询物资市场价完整信息（包含明细信息）
        getBasicDataList () {
            this.$Ajax
                .httpGet({
                    url: '/material/marketPrice/listById',
                    params: {
                        id: this.basicFormData.billId || this.billid,
                    },
                })
                .then(res => {
                    res.forEach(item=>{
                        this.marketPriceList.push(item)
                        this.basicFormData.marketPrice = item.marketPrice
                        this.basicFormData.onlinePrice = item.onlinePrice
                    })
                    // this.marketPriceList = res
                    // this.marketPriceList.forEach(item=>{
                    //     this.basicFormData.marketPrice = item.marketPrice
                    //     this.basicFormData.onlinePrice = item.onlinePrice
                    // })

                })
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
            document.getElementById('evaluateCon').offsetHeight
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },

        ctDelete () {
            if(this.marketPriceList.length === 0) {
                this.clientPop(
                    'info',
                    this.oneDeleteErr,
                    this.delData
                )
            }else{

                this.marketPriceList.forEach(item=>{
                    if(item.state === 1) {
                        this.clientPop('err', '市场价数据已被使用，不允许删除单据!')
                    }else{
                        this.clientPop(
                            'info',
                            this.oneDeleteErr,
                            this.delData
                        )
                    }
                })
            }
        },
        //根据物资市场价id删除物资市场价
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/material/marketPrice/delete',
                    params: {
                        id: this.basicFormData.billId,
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                })
                .then(res => {
                    if (res.code == 200) {
                        this.clientPop('suc', '删除成功', this.cancel)
                    }
                })
        },
        //生成id
        getId () {
            this.$Ajax
                .httpGet({
                    url: '/uid/builder',
                    params: {
                        num: 1,
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                }).then(res=>{
                    // res.forEach(item=>{
                    //     this.UidArr.push(item)
                    // })
                    this.basicFormData.billId = res[0]
                })
        },

        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        //关闭
        cancel () {
            this.dialogVisible = false
            this.$router.replace('./materialsMarketPrice')
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.billId
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },

        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },

        //获取当前时间
        geyDate () {
            var myDate = new Date()
            var y = myDate.getFullYear()
            var m = myDate.getMonth() + 1
            var d = myDate.getDate()
            var date = `${y}-${m}-${d}`
            return date
        },
    },
}
</script>

<style lang="scss" scoped>
.buttons {
  left: 0;
}
.e-form {
  margin-bottom: 80px;
  padding: 0 20px;
  .tabs-title::before {
    content: "";
    height: 22px;
    width: 8px;
    border-radius: 40px;
    background-color: #2e61d7;
    display: block;
    position: absolute;
    left: 20px;
    margin-right: 20px;
  }
}

.e-table {
  background: #fff;
}
::v-deep.el-table .warning-row {
  display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px; // 横向滚动条
  height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 5px;
}

.el-tab-pane {
  margin-left: -10px;
}
</style>